from flask_sqlalchemy import SQLAlchemy
import datetime


db = SQLAlchemy()

class BaseMixin(object):
	id = db.Column(db.BigInteger, primary_key=True)
	created_at = db.Column(db.DateTime, nullable=False,
						   default=datetime.datetime.now)
	updated_at = db.Column(db.DateTime, nullable=False, onupdate=datetime.datetime.now,
						   default=datetime.datetime.now)

	@property
	def small_allow_list(self):
		return ["id"]

	@classmethod
	def available(cls):
		res = cls.query
		if hasattr(cls, "weight") is True:
			res.order_by(desc("weight"))
		if hasattr(cls, "position") is True:
			res.order_by(desc("position"))
		return res

	@classmethod
	def paginate(cls, page=1, per_page=20, ilike=None, **data):
		if ilike is not None and ilike in data.keys():
			value = data[ilike]
			del data[ilike]
		res = cls.available().filter_by(**data)
		if ilike is not None and ilike in data.keys():
			res = res.filter(getattr(cls, ilike).ilike('%{}%'.format(value)))
		pag = res.paginate(page, per_page, error_out=False)
		info = [x.to_dict() for x in pag.items]
		return info, pag.total

	@classmethod
	def get_object_by_id(cls, id):
		res = cls.available().filter_by(id=id).first()
		return res

	@classmethod
	def by_id_to_dict(cls, id, method="completed"):
		res = cls.get_object_by_id(id)
		if method == "completed":
			return res._to_dict() if res is not None else {}
		elif method == "small":
			return res._to_dict_small() if res is not None else {}

	@classmethod
	def save_data(cls, data):
		obj = cls(**data)
		db.session.add(obj)
		try:
			db.session.commit()
		except Exception as e:
			db.session.rollback()

	def _to_dict(self):
		dict = {}
		dict.update(self.__dict__)
		if "_sa_instance_state" in dict:
			del dict['_sa_instance_state']
		if "birthdate" in dict and dict["birthdate"] is not None:
			dict["birthdate"] = self.birthdate.strftime("%Y-%m-%d %H:%M:%S")
		del dict["created_at"]
		del dict["updated_at"]
		return dict

	def _to_dict_small(self):
		res = dict()
		temp = self._to_dict()
		for item in self.small_allow_list:
			res[item] = temp[item]
		return res

	# 返回dict格式
	def to_dict(self, method="complete"):
		if method == "complete":
			dict = self._to_dict()
			if "user_id" in dict.keys():
				from .user import User
				dict["user_info"] = User.by_id_to_dict(dict["user_id"], "small")

			if "college_id" in dict.keys():
				from .canvas_new import College
				dict["college_info"] = College.by_id_to_dict(dict["college_id"], "small")

			dict["created_at"] = self.created_at.strftime("%Y-%m-%d %H:%M:%S")
			dict["updated_at"] = self.updated_at.strftime("%Y-%m-%d %H:%M:%S")
		elif method == "small":
			dict = self._to_dict_small()
		return dict

